package com.maysham.tripod.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.ResponseErrorHandler;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;

@Slf4j
public class RestErrorHandler implements ResponseErrorHandler {
    @Override
    public boolean hasError(ClientHttpResponse clientHttpResponse) throws IOException {
        return false;
    }

    @Override
    public void handleError(ClientHttpResponse clientHttpResponse) throws IOException {
        InputStream body = clientHttpResponse.getBody();
        StringBuilder stringBuilder = new StringBuilder();
        int len = -1;
        byte[] buffer = new byte[1024 * 5];
        while ((len = body.read(buffer)) != -1) {
            stringBuilder.append(new String(Arrays.copyOfRange(buffer, 0, len)));
        }
        log.error("请求异常：[{}],[{}]", clientHttpResponse.getStatusText(), stringBuilder.toString());
    }
}
